//1、安装依赖模块
var express = require('express');  //引入express
var bodyParser = require('body-parser');
var port = 3000;
//2、创建express实例
var app = express();
var arr = [
    {title:'标题1',user:'Jack',date:'2023-11-03',id:4},
    {title:'标题2',user:'Lily',date:'2023-11-07',id:2}
];
//3、跨域中间件
app.use(function(req,res,next){
    //允许所有来源进行跨域请求
    res.setHeader('Access-Control-Allow-Origin', '*');
    //允许特定http方法
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    //允许特定请求头
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token');
    next();
})
app.use(bodyParser.json());
//4、设置路由
app.get('/', function(req, res){
    res.send('hello world!');
})

//查询
app.get('/get_list', function(req, res){
    var data = {
        code:'200',
        msg:'success',
        result:arr
    }
    res.send(JSON.stringify(data));
})

//添加
app.post('/data/add',function(req,res){
    //添加id
    var _id = arr.length>0?Math.max(...arr.map(item=>item.id))+1:1;
    arr.push({...req.body,_id});
    res.send(JSON.stringify({code:'200',msg:'success'}));
})

//删除
app.delete('/data/del',function(req,res){
    arr = arr.filter(item => item.id != req.body.id)
    res.send(JSON.stringify({code:'200',msg:'success'}));
})

//all
app.get('/get1',function(req,res){
    var data = {
        code:'200',
        msg:'success',
        id:1
    };
    res.send(JSON.stringify(data));
})
app.get('/get2',function(req,res){
    var data = {
        code:'200',
        msg:'success',
        result:arr
    };
    res.send(JSON.stringify(data));
})

//5、监听端口
app.listen(port, function(){
    console.log('监听3000端口');
})